import { NextResponse } from 'next/server';
import { supabase } from '@/controller/supabase';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const projectId = searchParams.get('projectId');

  if (!projectId) {
    return NextResponse.json({
      success: false,
      error: true,
      message: '缺少项目ID参数',
      data: null
    }, { status: 400 });
  }

  try {
    const insertData = async () => {
      await supabase
        .from('projects')
        .update({
          search_keywords: ["人工智能", "新能源汽车", "机器学习"],
          matching_rules: ["规则1 AI相关的文章", "规则2 发布99条AI文章", "规则3 点赞数大于300"],
          update_time: new Date().toISOString()
        })
        .eq('project_id', projectId)
        .select()
        .single();
    }

    const insterTask = async () => {
      await supabase
        .from('tasks')
        .insert([
          {
            project_id: projectId,
            task_type: 'search',
            input_data: { "页数": 1, "关键词": "人工智能" },
            output_data: { "状态": "成功", "输出": "初始化完成" },
            status: 'PENDING',
            create_time: new Date().toISOString(),
            update_time: new Date().toISOString()
          }
        ])
        .select()
        .single();
    }
    // 模拟API处理延迟
    await new Promise(resolve => setTimeout(resolve, 2000));
    await insertData();
    await insterTask();

    return NextResponse.json({
      success: true,
      error: false,
      message: '关键词创建成功',
      data: null
    });
  } catch (error) {
    console.error('AI处理错误:', error);
    return NextResponse.json({
      success: false,
      error: true,
      message: '处理请求时出错',
      data: null
    }, { status: 500 });
  }
}
